import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, message, Input, Form, Space,Radio,Select,DatePicker } from 'antd';
import * as G from '../../../utils/common';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const mapStateToProps = (state: any) => ({
    user: state.user,
    menu: state.menu,
    collectionConfiguration: state.collectionConfiguration,
    loading: state.loading.effects['collectionConfiguration'],
});
class CollectionConfigurationExportModal extends PureComponent<any, any> {

    formRef = React.createRef<FormInstance>();
    
    constructor(props: any) {
        super(props);
        this.state = {
            vin: null,//车辆vin
            vehicleId: null,
            options: [],
            dates: null,//已选择的开始日期
            value: null,
            fieldList: [],
        };
    }

   
    componentDidMount() {
    }
    componentWillMount() {
        const { dispatch } = this.props;
        //获取采集车辆组列表
        dispatch({
          type: 'collectionConfiguration/getDataWithRes',
          payload: { url: '/data/collection/vehicle/allList' },
          callback: (e:any) => {
            const arr: any = [];
            e.data.map((d:any)=>{
                arr.push({
                    label: d.vehicleGroupName,
                    value: d.id
                })
            })
            this.setState({
                options: arr
                    
                })
            }
          },
        );
        //获取字段集列表
      this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/dict/finddictlistbycode',
        dictCode: 'searchType',
      },
      callback: (response:any) => {
        if (response && response.statusCode == '0') {
          this.setState({
            fieldList: response.data || [],
          });
        }
      },
       });
      }
    submitForm = () => {
        this.formRef.current?.submit();
    }

    ok = (values: any) => {
        const {vin, vehicleId}= this.state;
        const {dispatch}=this.props;
        const obj = { ...values };
        if(obj.type == 0){
          if(!vin){
            message.error("请输入VIN！");
            return;
          }
        }
        if(obj.type == 1){
            if(!vehicleId){
              message.error("请选择车辆组！");
              return;
            }
          }
        const params = {};
        if(obj.type == 0){
            params['vin']= vin;
          }
        if(obj.type == 1){
            params['vehicleId']= vehicleId; 
        }
        params['searchType']= obj.field;
        if (G.isNotEmptyAndNil(obj.rangetime)) {
            const [start, end] = obj.rangetime;
            // params['startTime'] = moment(start).format('YYYY-MM-DD');
            // params['endTime'] = moment(end).format('YYYY-MM-DD');
            params['searchDay'] = moment(start).format('YYYY-MM-DD');
          }
        dispatch({
            type: 'collectionConfiguration/postObjWithRes',
            payload: {
                url: '/data/collection/field/export',
                ...params
            },
            callback: (response: any) => {
                if (response.statusCode === '0') {
                    this.close();
                    message.success(response.statusMessage);
                    dispatch({
                        type: "collectionConfiguration/postFetchPage",
                        payload: { url: "/data/collection/config/list" }
                    })
                }
            }
        })
        this.close();
    }
       
    close = () => {
        const { closeModal } = this.props;
        closeModal();
        this.formRef.current?.resetFields();
        this.setState({
            vin: null,
            vehicleId: null
        })
    }
    checkFill = (rule, value, callback) => {
        const type =  this.formRef.current?.getFieldValue('type');
        if (!(type == 0 || type == 1)) {
          callback('请至少选择一项执行车辆类型！');
          return;
        }
        callback();
      };
    //禁用日期
    disabledDate = (current:any) => {
        const {dates}=this.state;
        const type =  this.formRef.current?.getFieldValue('type');
        if (!dates || !dates[0] && !dates[1]) {
            return current && current > moment().endOf('day');
          }else{
          if(type == 0){
          const tooLate = dates[0] && current.diff(dates[0], 'days') >= 1;
          const tooEarly = dates[1] && dates[1].diff(current, 'days') >= 1;
          return !!tooEarly || !!tooLate;
          }else if(type == 1){
            const tooLate = dates[0] && current.diff(dates[0], 'days') >= 1;
            const tooEarly = dates[1] && dates[1].diff(current, 'days') >= 1;
            return !!tooEarly || !!tooLate;
          }else{
            return current && current > moment().endOf('day');
          } 
        }
    }
    onOpenChange = (open: boolean) => {
        if (open) {
            this.setState({
                dates: [null, null]
            })
            this.formRef.current?.setFieldsValue({ rangetime: [null, null] });
        } else {
            this.setState({
                dates: null
            })
            const date = this.formRef.current?.getFieldValue('rangetime');
            const {value} = this.state;
            if (!date || !date[0]) this.formRef.current?.setFieldsValue({ rangetime: value });
        }
      };
    render() {
        const { modalVisible, loading, msg } = this.props;
        const {value, dates}=this.state;
        const options = (this.state.options || []).map((d:any) => (
            <Option key={d.value}>{d.label}</Option>
          ));
        const fieldList =  (this.state.fieldList || []).map((d:any) => (
          <Option key={d.dictKey}>{d.dictValue}</Option>
        ));
        const footer = (
            <div>
                <Button size="small" onClick={this.close}>取消</Button>
                <Button size="small" loading={loading} onClick={this.submitForm} type="primary">确认</Button>
            </div>
        );
        return (
            <Modal
                style={{ top: 20 }}
                width={700}
                footer={footer}
                title="导出字段"
                visible={modalVisible}
                onCancel={this.close}
            >
                <Form
                   labelCol={{
                    span: 6,
                  }}
                  wrapperCol={{
                    span: 18,
                  }}
                    ref={this.formRef}
                    onFinish={this.ok}
                >
            <Form.Item label="指定车辆"  required>
                 <Form.Item name="type" 
                 noStyle 
                 rules={[{ validator: this.checkFill }]}
                 initialValue={0}
             >
                  <Radio.Group>
                    <Space direction="vertical">
                       <Space>
                       <Radio value={0} >
                        <div style={{width: '45px'}}>
                        单车
                        </div>
                        </Radio>
                        <Input 
                        style={{width: '200px',borderColor: '#e9e7e7 !important'}}
                        placeholder="请输入VIN"
                        // value ={vin} 
                        onChange={(e) =>{
                            e.persist()
                            if(e){
                            this.setState({
                                vin: e.target.value
                            })
                            }else{
                                this.setState({
                                    vin: null
                                })
                            }
                        }}
                        />
                        </Space>
                        <Space>
                        <Radio value={1}>
                        <div style={{width: '45px'}}>
                       车辆组
                       </div>
                       </Radio>
                       <Select
                        placeholder="请选择车型组"
                        style={{width: '200px',borderColor: '#e9e7e7 !important'}}
                        allowClear
                        onChange={(e) =>{
                            if(e){
                            this.setState({
                              vehicleId: e
                            })
                            }else{
                                this.setState({
                                  vehicleId: null
                                })
                            }
                        }}
                     >
                          {options}
                       </Select>
                       </Space>
                    </Space>
                  </Radio.Group>  
                 </Form.Item>
                 </Form.Item>  
                 <Form.Item label="时间范围"  name="rangetime" rules={[{ required: true, message: '请选择时间范围' }]} required>
                 <RangePicker
                        style={{ width: '50%' }}
                        placeholder={['开始时间', '结束时间']}
                        format="YYYY-MM-DD"
                        value={dates || value}
                        disabledDate={this.disabledDate}
                        onCalendarChange={(val) => this.setState({dates: val})}
                        onChange={(val) => this.setState({value: val})}
                        onOpenChange={this.onOpenChange}
                      />
                </Form.Item>  
                <Form.Item label="字段集"  name="field" rules={[{ required: true, message: '请选择字段集' }]} required>
                <Select
                        placeholder="请选择字段集"
                        style={{width: '200px'}}
                        allowClear
                     >
                          {fieldList}
                       </Select>
                </Form.Item>   
             </Form>
            </Modal>
        );
    }
}
export default connect(mapStateToProps)(CollectionConfigurationExportModal);